/**
 
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
export var findAnagrams = function (s, p) {
  const countP = charCount(p)
  const n = p.length
  const ans = []
  let [left, right] = [0, n - 1]
  outer: while (right < s.length) {
    const constS = new Array(26).fill(0)
    for (let i = left; i <= right; i++) {
      const ch = s.charCodeAt(i) - 97
      if (countP[ch] === 0) {
        left = i + 1
        right = left + n - 1
        continue outer
      }
      constS[ch]++
    }
    if (arrayEqual(constS, countP)) {
      ans.push(left)
    }
    left++
    right++
  }
  return ans
}

function arrayEqual(a, b) {
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false
  }
  return true
}

function charCount(s) {
  const chars = new Array(26).fill(0)
  for (let i = 0; i < s.length; i++) {
    chars[s.charCodeAt(i) - 97]++
  }
  return chars
}
